package org.noear.quarkus.filter;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.RequestScoped;
import org.apache.commons.lang3.time.StopWatch;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

// @RequestScoped 相当于springboot里的  ThreadLocal<Context> threadLocal 的作用
@RequestScoped
public class StopWatchContext {

    // 计时对象
    StopWatch stopWatch;
    // 短唯一ID（1小时内不重复）
    String traceId;

    Boolean ck = false;

    // 随机字符池（数字+大小写字母，避免易混淆字符）
    private static final String RANDOM_CHARS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
    private static final Random RANDOM = new Random();
    // 时间格式：HHmmss（6位，小时+分钟+秒）
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");


    /**
     * 请求开始前
     */
    @PostConstruct
    void init() {
        this.stopWatch = StopWatch.createStarted();
        // 初始化唯一ID
        this.traceId = generateShortUniqueId();
    }

    public void ck(){
        ck=true;
    }

    /**
     * 一次请求结束后
     */
    @PreDestroy
    void destroy() {
        stopWatch = null;
    }


    public StopWatch get(){
        return stopWatch;
    }

    public String getTraceId() {
        return traceId;
    }

    /**
     * 生成短唯一ID：6位时间（HHmmss）+ 2位随机字符 = 8位
     */
    private String generateShortUniqueId() {
        // 1. 获取当前时间的HHmmss（6位）
        String timePart = LocalTime.now().format(TIME_FORMATTER);
        // 2. 生成2位随机字符
        StringBuilder randomPart = new StringBuilder(2);
        for (int i = 0; i < 2; i++) {
            int index = RANDOM.nextInt(RANDOM_CHARS.length());
            randomPart.append(RANDOM_CHARS.charAt(index));
        }
        // 拼接结果（如：143522a7）
        return timePart + randomPart;
    }
}
